package com.emr.common;

import java.net.URL;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

/**
 * 使用Spring对象Bean
 * @author Hearken
 * @date Oct 9, 2010 4:22:36 PM
 */
public class SpringBean {
	
	private static ApplicationContext ctx;
	
	static {
		URL classurl = ApplicationContext.class.getResource("/");
		setCtx(classurl.toString());
	}
	
	/**
	 * 获取spring配置的bean
	 * @param beanName
	 * @return
	 */
	public static Object getBean(String beanName) {
		return getCtx().getBean(beanName);
	}
	
	/**
	 * 获取程序上下文
	 * @return
	 */
	public static ApplicationContext getCtx() {
		return ctx;
	}
	
	/**
	 * 设置程序上下文
	 * @param classpath
	 */
	public static void setCtx(String classpath) {
		if (ctx == null) {
			System.out.println("-----加载Spring相关对象 开始-----");
			ctx = new FileSystemXmlApplicationContext(classpath + "applicationContext.xml");
			System.out.println(classpath + "applicationContext.xml");
			System.out.println("-----加载Spring相关对象 结束-----");
		}
	}
	
	/**
	 * 程序调试时使用，属于临时性的程序
	 */
	public void setCtx2() {
		if (ctx == null) {
			ctx = new FileSystemXmlApplicationContext("/WebRoot/WEB-INF/classes/applicationContext.xml");
		}
	}
	
	
	/**
	 * 获取事务管理器
	 * @return
	 */
	public static PlatformTransactionManager getTransactionManager() {
		PlatformTransactionManager ptm = null;
		try {
			ptm = (PlatformTransactionManager) getBean("transactionManager");
		} catch (Exception e) {
			System.out.println("获取事务管理器：" + e.getMessage());
		}
		return ptm;
	}
	
	/**
	 * 获取事务状态
	 * @return
	 */
	public static TransactionStatus getTransactionStatus(PlatformTransactionManager ptm) {
		TransactionStatus status = null;
		try {
			if (ptm == null) { return status; }
			DefaultTransactionDefinition dtd = new DefaultTransactionDefinition();
			status = ptm.getTransaction(dtd);
		} catch (TransactionException e) {
			System.out.println("获取事务状态：" + e.getMessage());
		}
		return status;
	}
}